package net.caixiaomi.info.ui.withdraw;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.ManagerCardAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.BaseAlertDialog;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.ManagerCardModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;

/**
 * 管理银行卡
 */

public class ManagerCardActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener, View.OnClickListener, OnRefreshListener {

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;

    @BindView(android.R.id.list)
    RecyclerView mListView;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    private ManagerCardAdapter mAdapter;
    private List<ManagerCardModel> mData = new ArrayList<>();

    @Override
    protected int layout() {
        return R.layout.act_withdraw_manager;
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View footer = LayoutInflater.from(this).inflate(R.layout.footer_add_card, null);
        footer.setOnClickListener(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = (int) getResources().getDimension(R.dimen.padding_8);
        layoutParams.bottomMargin = (int) getResources().getDimension(R.dimen.padding_8);
        footer.setLayoutParams(layoutParams);
        mLoading = new DefLoading(this);
        mRefresh.setOnRefreshListener(this);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ManagerCardAdapter(R.layout.item_manager_card, mData);
        mAdapter.addFooterView(footer);
        mAdapter.setHeaderFooterEmpty(false, true);
        mAdapter.setOnItemChildClickListener(this);
        mListView.setAdapter(mAdapter);
        loadData();
    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("time", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<ManagerCardModel>>> userBankList = requestService.queryUserBankList(params);
        userBankList.enqueue(new ResponseCallback<BaseCallModel<List<ManagerCardModel>>>(this) {
            @Override
            public void onSuccess(BaseCallModel<List<ManagerCardModel>> data) {
                mLoading.dismiss();
                mProgress.setVisibility(View.GONE);
                mRefresh.setVisibility(View.VISIBLE);
                mRefresh.finishRefresh();
                if (data.data != null) {
                    mData.clear();
                    mData.addAll(data.data);
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                mRefresh.finishRefresh();
                mProgress.setVisibility(View.GONE);
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mLoading.dismiss();
                mRefresh.finishRefresh();
                mProgress.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        super.onPostEvent(event);
        switch (event.getWhat()) {
            case EventWhat.EVENT_ADD_BANK_CARD:
                onRefresh();
                break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            ManagerCardModel item = mData.get(position);
            switch (view.getId()) {
                case R.id.selected:
                    changeStatus(item);
                    break;
                case R.id.btn_close:
                    showDeleteDialog(item);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void changeStatus(ManagerCardModel item) {
        try {
            if (TextUtils.equals("1", item.getStatus()))
                return;
            mLoading.show();
            JSONObject params = new JSONObject();
            params.put("id", item.getUserBankId());
            RequestService requestService = RetrofitManage.getInstance().getRequestService();
            Call<BaseCallModel> updateUserBankDefault = requestService.updateUserBankDefault(params);
            updateUserBankDefault.enqueue(new ResponseCallback<BaseCallModel>(this) {
                @Override
                public void onSuccess(BaseCallModel data) {
                    ToastUtil.s(data.msg);
                    onRefresh();
                }

                @Override
                public void onFail(ResponseError error) {
                    if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                        ToastUtil.s(error.getMessage());
                    }
                }

                @Override
                public void onError() {
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deleteCard(ManagerCardModel item) {
        mLoading.show();
        JSONObject params = new JSONObject();
        params.put("id", item.getUserBankId());
        params.put("status", item.getStatus());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<ManagerCardModel>> deleteUserBank = requestService.deleteUserBank(params);
        deleteUserBank.enqueue(new ResponseCallback<BaseCallModel<ManagerCardModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<ManagerCardModel> data) {
                mLoading.dismiss();
                ManagerCardModel model = data.data;
                if (model != null && !TextUtils.isEmpty(model.getUserBankId())) {
                    showDeleteDoneDialog(model);
                } else {
                    ToastUtil.s(data.msg);
                }
                onRefresh();
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });
    }

    private void showDeleteDoneDialog(final ManagerCardModel item) {
        String text = getString(R.string.C_WITHDRAW_DELETE_DEFAULT_CARD_DONE, item.getLastCardNo4(), item.getBankName());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.C_CARD_END_NUM)).append(item.getLastCardNo4());
        String term = stringBuilder.toString();
        int start = text.indexOf(term);
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), start, start + term.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.orange_primary)), text.length() - item.getBankName().length(), text.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

        BaseAlertDialog dialog = new BaseAlertDialog(this);
        dialog.setMessage(spannableString);
        dialog.setPositiveButton(R.string.C_I_KNOW, null);
        dialog.show();
    }

    private void showDeleteDialog(final ManagerCardModel item) {
        BaseAlertDialog dialog = new BaseAlertDialog(this);
        dialog.setMessage(TextUtils.equals("1", item.getStatus()) ? R.string.C_WITHDRAW_DELETE_DEFAULT : R.string.C_WITHDRAW_DELETE_NO_DEFAULT);
        dialog.setPositiveButton(R.string.C_DELETE, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteCard(item);
            }
        });
        dialog.setNegativeButton(R.string.C_CANCEL, null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }


    public void onRefresh() {
        loadData();
    }

    @Override
    public void onClick(View v) {
        AppHelper.sendStatistics("tianjiayinhangka");
        Intent intent = new Intent(this, AddCardActivity.class);
        startActivity(intent);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        loadData();
    }
}
